<template>
  <view>
    <scroll-view scroll-y class="page">
      <!-- 头部 -->
      <cu-custom bgColor="bg-rgb" :isBack="true">
        <block slot="backText">返回</block>
        <block slot="content">质检保存</block>
      </cu-custom>
      <!-- 数据列表 -->
      <!-- <view class="list"> -->
      <form @submit="onSubmitPrin">
        <view class="card animation-slide-bottom" :style="[{animationDelay: (index + 1)*0.1 + 's'}]">
          <!-- <view class="top">
            <view class="left">行号：<text>({{index +1}})</text></view>
          </view> -->

          <view class="cu-form-group">
            <!-- <view class="title">来料日期: 2021-02-03</view> -->
            <view class="title">物料编号:{{objMsg.materielCode}}</view>
            <view class="lable">
              <picker name="inMaterialType" dataType="1" @change="PickerChange" :value="index"
                      :range="typeArray">
                <view class="picker">
                  {{getChooseType}}
                </view>
              </picker>
            </view>
            <!-- <view class="lable">
                来料单号: xyz-32341
              </view> -->
          </view>
          <!-- 		 <view class="cu-form-group">
              <view class="title">校验日期: {{date}}</view>
              <view class="lable">
                <picker name="inMaterialType" dataType="1" @change="PickerChange" :value="index" :range="typeArray">
                  <view class="picker">
                    {{getChooseType}}
                  </view>
                </picker>
              </view>
            </view> -->
          <view class="cu-form-group">
            <!-- <view class="title">物料编号:{{objMsg.materielCode}}</view> -->
            <view class="lable">
              检测名称: {{projectNames.join('、')}}
            </view>
          </view>
          <view class="cu-form-group">
            <!-- <view class="title">物料编号:{{objMsg.materielCode}}</view> -->
            <view class="lable">
              物料名称: {{objMsg.materielName}}
            </view>
          </view>
          <view class="cu-form-group">
            <!-- <view class="title">物料编号:{{objMsg.materielCode}}</view> -->
            <view class="lable">
              数量: {{objMsg.inputNum}}
            </view>
          </view>
          <view class="flex borderTop">
            <view class="flex-sub margin-xs radius">
              <view class="cu-form-group">
                <view class="title">抽样数量</view>
                <input class="border" type="number" placeholder="" name="samplesNum"></input>
              </view>
            </view>
            <view class="flex-sub margin-xs radius">
              <view class="cu-form-group">
                <view class="title">是否HSF标示</view>
                <switch name="hsrfLabeling" @change="handleSwitchHsf" :class="switchHsf?'checked':''"
                        :checked="switchHsf?true:false"></switch>
              </view>
            </view>
          </view>
          <view class="cu-form-group">
            <view class="lable">
              原值: {{yuanzhi}}
            </view>
          </view>
          <view class="cu-form-group">
            <view class="title">测试值</view>
            <input class="border" placeholder="" name="testValue"></input>
          </view>
          <view class="flex p-xs margin-bottom-sm mb-sm borderTop">
            <view class="padding-sm margin-xs radius">允收数</view>
            <view class="flex-sub padding-sm margin-xs radius">
              <input class="border" type="number" placeholder="致命缺陷" name="accepNum1"></input>
            </view>
            <view class="flex-sub padding-sm margin-xs radius">
              <input class="border" type="number" placeholder="严重缺陷" name="accepNum2"></input>
            </view>
            <view class="flex-sub padding-sm margin-xs radius">
              <input class="border" type="number" placeholder="轻微缺陷" name="accepNum3"></input>
            </view>
          </view>
          <view class="flex p-xs margin-bottom-sm mb-sm borderTop">
            <view class="padding-sm margin-xs radius">拒收数</view>
            <view class="flex-sub padding-sm margin-xs radius">
              <input class="border" type="number" placeholder="致命缺陷" name="rejectionNum1"></input>
            </view>
            <view class="flex-sub padding-sm margin-xs radius">
              <input class="border" type="number" placeholder="严重缺陷" name="rejectionNum2"></input>
            </view>
            <view class="flex-sub padding-sm margin-xs radius">
              <input class="border" type="number" placeholder="轻微缺陷" name="rejectionNum3"></input>
            </view>
          </view>
          <template v-for="(item, index) in preservationList">
            <view class="flex p-xs margin-bottom-sm mb-sm borderTop">
              <view class="padding-sm margin-xs radius">{{item.projectName}}不良品数量</view>
              <view class="flex-sub padding-sm margin-xs radius">
                <input class="border" type="digit" placeholder="致命" name="rejectsNum1"
                       v-model="preservationList[index].rejectsNum1"></input>
              </view>
              <view class="flex-sub padding-sm margin-xs radius">
                <input class="border" type="digit" placeholder="严重" name="rejectsNum2"
                       v-model="preservationList[index].rejectsNum2"></input>
              </view>
              <view class="flex-sub padding-sm margin-xs radius">
                <input class="border" type="digit" placeholder="轻微" name="rejectsNum3"
                       v-model="preservationList[index].rejectsNum3"></input>
              </view>
            </view>
            <view class="cu-form-group align-start">
              <view class="title">缺陷描述</view>
              <textarea maxlength="-1" :disabled="modalName!=null" @input="textareaBInput"
                        placeholder="请输入" name="defectDesc"
                        v-model="preservationList[index].defectDesc"></textarea>
            </view>
          </template>
          <view class="cu-form-group align-start" style="padding-top: 10px;">
            <view class="title">拍照上传</view>
            <button @tap="takephoto()" class="cu-btn bg-rgb shadow lg" style="width: 100px;">拍照上传</button>
          </view>
          <view class="picture-box">
            <image :src="item" v-for="item in imglist"></image>
            <!-- <view v-for="item in imglist" class="picture"
                :style="{background: 'url(' + item + ') no-repeat',backgroundSize:'cover'}"></view> -->
          </view>
          <radio-group class="flex" @change="radioChange">
            <label class="flex-sub flex justify-center align-center margin-xs padding-sm"
                   v-for="(item, index) in radioItems" :key="item.value">
              <view class="margin-right-sm">
                <radio :value="item.value" :checked="index === radioCurrent" />
              </view>
              <view>{{item.name}}</view>
            </label>
          </radio-group>
          <!-- <view class="cu-form-group align-start">
              <view class="title">外观缺陷描述</view>
              <textarea maxlength="-1" :disabled="modalName!=null" @input="textareaBInput" placeholder="请输入" name="appearanceDescribe"></textarea>
            </view>
            <view class="cu-form-group align-start">
              <view class="title">尺寸缺陷描述</view>
              <textarea maxlength="-1" :disabled="modalName!=null" @input="textareaBInput" placeholder="请输入" name="sizeDescribe"></textarea>
            </view>
            <view class="cu-form-group align-start">
              <view class="title">功能缺陷描述</view>
              <textarea maxlength="-1" :disabled="modalName!=null" @input="textareaBInput" placeholder="请输入" name="functionDescribe"></textarea>
            </view> -->



          <!-- <view class="bottom">
            <view class="boxs">
              <view class="lable">
                <text class="title" style="background-color: #99CC00;">检测结果：</text>
              </view>
              <view class="content">
                <textarea style="width: 400rpx;" v-model="preservationList[index].txt" value="" placeholder="请输入质检结果" />
              </view>
            </view>
          </view> -->
        </view>
        <view class="btns">
          <button form-type="submit" class="cu-btn bg-rgb shadow lg">保存</button>
        </view>
      </form>
      <!-- </view> -->
      <!-- <view class="btns">
        <button class="cu-btn bg-rgb lg" @click="onSubmitPrin">保存</button>
      </view> -->
    </scroll-view>
  </view>
</template>

<script>
export default {
  /** 来料检验 */
  data() {
    const currentDate = this.getDate({
      format: true
    })
    return {
      date: currentDate,
      yuanzhi: '',
      index: -1,
      typeArray: ['电子', '五金', '塑胶', '包材', '辅料', 'SMT外加工'],
      switchHsf: false,
      inspectGrade: "",
      materielCode: '',
      list: [],
      preservationList: [],
      objMsg: {},
      modalName: null,
      projectNames: [],
      radioItems: [{
        value: '合格',
        name: '合格'
      },
        {
          value: '不合格',
          name: '不合格'
        },
        {
          value: '待定',
          name: '待定'
        }
      ],
      radioCurrent: 0,
      imglist: [],

    }
  },
  computed: {
    getChooseType() {
      return this.index === -1 ? '类型' : this.typeArray[this.index]
    }
  },
  onLoad(e) {
    this.objMsg = uni.getStorageSync('inspectDetailObj');
    console.log(this.objMsg)
    this.qualityTesting()
    this.yuanzhi = this.objMsg.materielGauge
  },
  methods: {
    takephoto() {
      let that = this
      let maxUpload = 1
      uni.chooseImage({
        count: 1, // 最多可以选择的图片张数，默认1
        sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
        sourceType: ['camera', 'album'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
        success: (res) => {
          console.log(res);
          const tempFilePaths = res.tempFilePaths
          tempFilePaths.forEach(item => {
            uni.uploadFile({
              url: that.$http.config.baseUrl + 'sys/common/upload',
              filePath: item,
              method: 'POST',
              name: 'file',
              header: {
                'X-Access-Token': uni.getStorageSync('Access-Token')
              },
              success: function(uploadFileRes) {
                that.imglist = []
                that.modal.show({
                  type: 'success',
                  content: '上传成功!'
                })
                let result = JSON.parse(uploadFileRes.data)
                if (result.success) {
                  that.imglist = that.imglist.concat([result
                      .message]); //concat追加到数组
                } else {
                  that.modal.show({
                    type: 'error',
                    content: result.message
                  })
                }
              }
            });
          })
        }
      });
    },
    getYuanzhi() {
      this.$http.get('/chiefdata/mesChiefdataBom/getMCodebomitem', {
        params: {
          materielCode: this.objMsg.materielCode
        }
      }).then(res => {
        if (res.data.success) {
          this.yuanzhi = res.data.result.materielGauge
        } else {
          this.modal.show({
            type: 'error',
            content: res.data.message
          })
        }
      })
    },
    radioChange: function(evt) {
      for (let i = 0; i < this.radioItems.length; i++) {
        if (this.radioItems[i].value === evt.target.value) {
          this.radioCurrent = i;
          break;
        }
      }
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 60;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    PickerChange(e) {
      this.index = e.target.value
    },
    PickerHsfChange(e) {
      this.hsfIndex = e.target.value
    },
    handleSwitchHsf(e) {
      this.switchHsf = e.detail.value
    },
    qualityTesting() {
      uni.showLoading({
        mask: true,
        title: '加载中.....'
      })
      let data = {
        inspectGrade: this.objMsg.mobileCode,
        materielCode: this.objMsg.materielCode
      }
      this.$http.get('inspect/mesMaterielCheckprojrct/getByGrade', {
        params: data
      }).then(res => {
        uni.hideLoading()
        if (res.data.success) {
          this.list = res.data.result
          for (let i = 0; i < this.list.length; i++) {
            let data = {
              num: '',
              rejectsNum1: '',
              rejectsNum2: '',
              rejectsNum3: '',
              defectDesc: '',
              id: this.list[i].id,
              projectName: this.list[i].projectName,
              projectCode: this.list[i].projectCode,
              mesIqcMaterial: {},
              query2: this.list[i].query2
            }
            this.projectNames.push(data['projectName'])
            this.preservationList.push(data)
          }
        } else {
          // this.$tip.error(res.data.message)
          this.modal.show({
            type: 'error',
            content: res.data.message
          })
        }
      })
    },
    textareaBInput(e) {
      this.textareaBValue = e.detail.value
    },
    onSubmitPrin(e) {
      e.detail.value.hsrfLabeling = '' + e.detail.value.hsrfLabeling
      let {
        samplesNum,
        origValue,
        testValue
      } = e.detail.value
      if (this.index === -1) {
        this.modal.show({
          type: 'error',
          content: '请选择类型'
        })
        return
      }
      if (samplesNum.trim().length === 0) {
        this.modal.show({
          type: 'error',
          content: '请输入抽样数量'
        })
        return
      }
      // if (origValue.trim().length === 0) {
      // 	this.modal.show({ type:'error', content:'请输入原值' })
      // 	return
      // }
      // if (testValue.trim().length === 0) {
      // 	this.modal.show({ type:'error', content:'请输入测试值' })
      // 	return
      // }
      uni.showModal({
        title: '质检保存',
        content: '是否本次质检合格记录？',
        cancelText: '取消',
        confirmText: '保存',
        success: res => {
          if (res.confirm) {
            uni.showLoading({
              mask: true,
              title: '保存中.....'
            })
            let {
              inMaterialType
            } = e.detail.value
            let obj = {
              inspectGrade: this.objMsg.mobileCode,
              materielCode: this.objMsg.materielCode,
              materielName: this.objMsg.materielName,
              relatedCode: this.objMsg.id,
              inspectQualify: this.radioItems[this.radioCurrent].value === '合格' ? '是' : '否',
              mesIqcDefect: [],
              mesBadnessInfoList: [],
              mesIqcInfo: {
                inMaterialType: this.typeArray[inMaterialType],
                inspectionDate: this.date,
                imglist: this.imglist[0],
              },
              mesIqcMaterial: {
                origValue: this.yuanzhi,
                isQualified: this.radioItems[this.radioCurrent].value,
                ...e.detail.value
              }
            }
            for (let i = 0; i < this.preservationList.length; i++) {
              let data = {
                // badCode: this.preservationList[i].code,
                defectTypeName: this.preservationList[i]
                    .projectName,
                // inspectProject: this.preservationList[i].code + '-' +this.preservationList[i].name,
                defectDesc: this.preservationList[i]
                    .defectDesc,
                rejectsNum1: this.preservationList[i]
                    .rejectsNum1,
                rejectsNum2: this.preservationList[i]
                    .rejectsNum2,
                rejectsNum3: this.preservationList[i]
                    .rejectsNum3,
                sysOrgCode: this.preservationList[i].query2
              }
              obj.mesIqcDefect.push(data);
            }
            // console.log('post:', obj)
            // return;
            this.$http.post('inspect/mesBadnessHandle/appAdd', obj)
                .then(res => {
                  uni.hideLoading()
                  if (res.data.success) {
                    // this.$tip.success(res.data.message);
                    this.modal.show({
                      type: 'success',
                      content: res.data.message
                    })
                    if(this.radioItems[this.radioCurrent].value === '合格'){
                      setTimeout(function() {
                        uni.navigateBack({
                          delta: 1
                        })
                      }, 1000);
                    }else{
                      this.$Router.push({
                        name: 'disqualification',
                        params:{
                          objMsg:this.objMsg,
						  type:'不合格退料'
                        }
                      })
                    }
                  } else {
                    // this.$tip.error(res.data.message)
                    this.modal.show({
                      type: 'error',
                      content: res.data.message
                    })
                  }
                })
          }
        }
      })

    },
    formSubmit(e) {
      console.log('form发生了submit事件，携带数据为：' + JSON.stringify(e.detail.value))
    }

  },
}
</script>

<style lang="less">
.inlinbl {
  display: inline-block;
}

.padding-sm {
  padding: 11px 0;
}

.borderTop {
  border-top: 0.5px solid #eee;
}

.border {
  border: 0.5px solid #eee;
}

.cu-form-group {
  padding: 0.5px 0;

  .title {
    height: auto;
    text-align: left;
  }
}

.picture-box {
  width: 100%;
  margin-top: 10px;

  .picture {
    width: 100%;
    height: 200px;
    margin-bottom: 10px;
  }
}

.card {
  // margin: 30rpx;
  box-shadow: 0px 0px 5rpx 2rpx rgba(0, 0, 0, 0.1);
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 100rpx;
  background-color: white;
}

.card .top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #F0F0F0;
  padding-bottom: 20rpx;
  font-weight: bold;
}

.top .left {
  font-size: 28rpx;
  font-family: PingFang SC;
  font-weight: 400;
  color: #485A75;
  line-height: 50rpx;
}

.card .bottom .box {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
}

.card .bottom .box .lable {
  width: 25%;
}

.card .bottom .box .content {
  width: 74%;
  text-align: right;
}

.boxs {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  align-items: center;
}

.boxs .title {
  font-weight: bold;
  padding: 10rpx;
  border-radius: 10rpx;
  color: white;
;
}

.boxs input {
  border: 2rpx solid red;
  height: 60rpx;
  padding: 10rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
  color: red;
}

.boxs input .input-placeholder {
  color: red;
}

uni-textarea {
  border: 2rpx solid #F0F0F0;
  padding: 10rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
}

.list {
  margin-bottom: 120rpx;
}

.btns {
  position: fixed;
  width: 100%;
  padding: 0 16px;
  z-index: 999;
  background: white;
  bottom: 0;
  height: 100rpx;
  line-height: 100rpx;
}

.cu-btn {
  width: 100%;
  // margin-left: 50rpx;
}
</style>
